<?php

class PaymentTtCompletedAction extends SzAbstractAction
{
    protected $paramTypes = array();


    public function execute()
    {
        $satrt_date = date("Y-m-d H:i:s", GameService::get()->getSysTime());
        error_log('CallBackStart****start_date==>' . $satrt_date . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

        $RDataArray = SzParam::getWholeRequest();
        $bodyData = @file_get_contents('php://input');
        $DataArray = json_decode($bodyData, true) ?? [];

        if (!empty($RDataArray)) {
            $DataArray = array_merge($DataArray, $RDataArray);
        }

        $timestamp = $DataArray['timestamp'];
        $nonce = $DataArray['nonce'];
        $msg = $DataArray['msg'];
        $token = '52d0ee3c031dd';
        $echostr = $DataArray['echostr'];
        $signature = $DataArray['signature'];
        error_log('ttComplete_request==>' . "\r\n" . json_encode($DataArray) . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

        $params = array(
            'nonce' => $nonce,
            'timestamp' => $timestamp,
            'msg' => $msg,
            'token' => $token,
        );
        ksort($params); //按字母升序排序

        $str = implode('', $params);
        $checkSign = sha1($str);
        error_log('ttComplete_checkSign==>' . "\r\n" . $checkSign . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

        $msgArray = json_decode($msg, true);
        $appid = $msgArray['appid'];
        $cp_orderno = $msgArray['cp_orderno'];//开发者自定义订单号
        $cp_extra = $msgArray['cp_extra'];//开发者传的额外参数
        error_log('ttComplete_request_msg==>' . "\r\n" . json_encode($msgArray) . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

        if ($cp_orderno) {
            //充值结果查询
            $response = PlatformTT::get()->queryPay($cp_orderno);
            error_log("\r\n\r\n" . 'ttComplete_response==>' . "\r\n" . json_encode($response) . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
            $status = $response['data']['status'];
            error_log('ttComplete_status==>' . $status . "\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

            if ($status == 'success') {
                $reqTime = GameService::get()->getSysTime();
                //获取订单的用户userid
                $serversConfigs = SzConfig::get()->loadAppConfig('database', 'Payment');
                $instance1 = new SzMySqlDb($serversConfigs);
                $userId_info = $instance1->select("SELECT `userId`  FROM `module_payment_order` where `paymentDefId`='{$cp_orderno}'");
                $userId = $userId_info[0]['userId'];
                error_log('userId ==>' . $userId . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
                //查询数据库，订单是否存在
                /**
                 * @var ModulePaymentOrderVoList $paymentList
                 * @var ModulePaymentOrderVo $payment
                 */
                $paymentList = SzPersister::get()->getVoList($userId, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER);
                $paymentDatas = $paymentList->toArray();
                $orderData = array();
                foreach ($paymentDatas as $id => $data) {
                    if ($cp_orderno == $data['paymentDefId']) {
                        $orderData = $data;
                        break;
                    }
                }
                if (empty($orderData)) {
                    SzLogger::get()->error('orderData - is empty');
                    echo 'result=FAIL&resultMsg=4+OrderNonexistent';
                    exit();
                }

                $payment = $paymentList->getElement($orderData['orderId'], false);
                $getParams = json_decode($payment->getExtra(), true);//ext扩展信息，json格式
                $userId = $getParams['userId'];
                $price = $getParams['price'];
                $type = $getParams['type'];
                $goodId = $getParams['goodId'];
                $count = $getParams['count'];
                $isFirstPay = $getParams['isFirstPay'];
                $platform = $getParams['platform'];

                //扣除游戏币
                $amt = $payment->getPrice();
                //充值测试白名单
                if (in_array($userId, GameConst::GAME_TT_TEST_USERID)) {
                    $amt = 1;
                }

                $deductRes = PayTtService::get()->ttDeduct($userId, $amt, $cp_orderno, $platform, $reqTime);
                error_log('ttComplete_Deduct==>' . "\r\n" . json_encode($deductRes) . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

                //修改订单状态，并发放道具
                $orderId = $payment->getOrderId();
                error_log('ttComplete_orderId==>' . $orderId . "\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
                PayTtCompletedService::get()->ttPayCompleted($userId, $orderId, 1);
            }
        }
        exit;
    }
}
